package gui;

import entity.Score;
import entity.Student;
import service.FileManager;
import service.ScoreAnalysis;
import service.ScoreManager;
import service.StudentManager;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import javax.swing.border.EmptyBorder;

/**
 * 学生管理系统主窗口
 */
public class MainFrame extends JFrame {
    private final ScoreManager scoreManager;
    private final StudentManager studentManager;
    private final FileManager fileManager;
    
    // 主面板
    private JPanel mainPanel;
    private CardLayout cardLayout;
    
    // 各功能面板
    private StudentPanel studentPanel;
    private ScorePanel scorePanel;
    private StatisticsPanel statisticsPanel;
    private DataPanel dataPanel;
    
    // 菜单组件
    private JMenuBar menuBar;
    private JMenu fileMenu, helpMenu, themeMenu; // 添加主题菜单
    private JLabel statusLabel; // 状态栏标签
    
    /**
     * 构造函数
     */
    public MainFrame(ScoreManager scoreManager, StudentManager studentManager, FileManager fileManager) {
        this.scoreManager = scoreManager;
        this.studentManager = studentManager;
        this.fileManager = fileManager;
        
        initUI();
    }
    
    /**
     * 初始化UI
     */
    private void initUI() {
        // 设置窗口基本属性
        setTitle("学生管理系统 - v2.0");
        setSize(1000, 700);
        setLocationRelativeTo(null); // 居中显示
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        
        // 设置窗口图标
        try {
            // 如果有图标文件，可以在这里设置
            // setIconImage(new ImageIcon("path/to/icon.png").getImage());
        } catch (Exception e) {
            // 忽略图标设置错误
        }
        
        // 设置窗口背景色
        getContentPane().setBackground(ThemeManager.BACKGROUND_COLOR);
        
        // 添加窗口关闭事件
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                int option = JOptionPane.showConfirmDialog(
                        MainFrame.this,
                        "是否要退出系统？",
                        "退出确认",
                        JOptionPane.YES_NO_OPTION);
                
                if (option == JOptionPane.YES_OPTION) {
                    System.exit(0);
                }
            }
        });
        
        // 创建卡片布局的主面板
        cardLayout = new CardLayout();
        mainPanel = new JPanel(cardLayout);
        
        // 创建各功能面板
        studentPanel = new StudentPanel(studentManager);
        scorePanel = new ScorePanel(scoreManager, studentManager);
        statisticsPanel = new StatisticsPanel(scoreManager, studentManager);
        dataPanel = new DataPanel(fileManager, scoreManager, studentManager);
        
        // 添加面板到主面板
        mainPanel.add(studentPanel, "student");
        mainPanel.add(scorePanel, "score");
        mainPanel.add(statisticsPanel, "statistics");
        mainPanel.add(dataPanel, "data");
        
        // 创建侧边栏导航
        JPanel sidebarPanel = createSidebar();
        
        // 使用分割面板组合侧边栏和主内容区
        JSplitPane splitPane = new JSplitPane(
                JSplitPane.HORIZONTAL_SPLIT,
                sidebarPanel,
                mainPanel
        );
        splitPane.setDividerLocation(200);
        splitPane.setDividerSize(5);
        splitPane.setOneTouchExpandable(true);
        
        // 创建菜单栏
        createMenuBar();
        
        // 创建状态栏
        JPanel statusBar = createStatusBar();
        
        // 添加组件到窗口
        add(splitPane, BorderLayout.CENTER);
        add(statusBar, BorderLayout.SOUTH);
        
        // 应用主题
        ThemeManager.applyThemeRecursively(this);
        
        // 显示默认面板
        cardLayout.show(mainPanel, "student");
        
        // 启动定时更新状态栏
        startStatusUpdate();
    }
    
    /**
     * 创建侧边栏导航
     */
    private JPanel createSidebar() {
        JPanel sidebar = new JPanel(new BorderLayout());
        sidebar.setBorder(BorderFactory.createEtchedBorder());
        
        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new GridLayout(6, 1, 5, 10));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // 创建导航按钮
        JButton studentBtn = createNavButton("学生信息管理", "student");
        JButton scoreBtn = createNavButton("成绩管理", "score");
        JButton statisticsBtn = createNavButton("统计分析", "statistics");
        JButton dataBtn = createNavButton("数据管理", "data");
        JButton exitBtn = new JButton("退出系统");
        
        // 退出按钮事件
        exitBtn.addActionListener(e -> {
            int option = JOptionPane.showConfirmDialog(
                    MainFrame.this,
                    "是否要退出系统？",
                    "退出确认",
                    JOptionPane.YES_NO_OPTION);
            
            if (option == JOptionPane.YES_OPTION) {
                System.exit(0);
            }
        });
        
        // 添加按钮到面板
        buttonPanel.add(studentBtn);
        buttonPanel.add(scoreBtn);
        buttonPanel.add(statisticsBtn);
        buttonPanel.add(dataBtn);
        buttonPanel.add(new JLabel()); // 空白占位
        buttonPanel.add(exitBtn);
        
        // 添加标题和按钮面板到侧边栏
        JLabel titleLabel = new JLabel("功能导航", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        titleLabel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
        
        sidebar.add(titleLabel, BorderLayout.NORTH);
        sidebar.add(buttonPanel, BorderLayout.CENTER);
        
        return sidebar;
    }
    
    /**
     * 创建导航按钮
     */
    private JButton createNavButton(String text, String panelName) {
        JButton button = new JButton(text);
        button.addActionListener(e -> cardLayout.show(mainPanel, panelName));
        return button;
    }
    
    /**
     * 创建菜单栏
     */
    private void createMenuBar() {
        menuBar = new JMenuBar();
        menuBar.setBackground(ThemeManager.PRIMARY_COLOR);
        
        // 文件菜单
        fileMenu = new JMenu("文件");
        fileMenu.setForeground(Color.WHITE);
        fileMenu.setFont(ThemeManager.NORMAL_FONT);
        
        JMenuItem saveItem = new JMenuItem("保存数据");
        JMenuItem loadItem = new JMenuItem("加载数据");
        JMenuItem backupItem = new JMenuItem("备份数据");
        JMenuItem exitItem = new JMenuItem("退出");
        
        // 设置菜单项样式
        for (JMenuItem item : new JMenuItem[]{saveItem, loadItem, backupItem, exitItem}) {
            item.setFont(ThemeManager.NORMAL_FONT);
        }
        
        saveItem.addActionListener(e -> {
            fileManager.saveStudent(studentManager.getStudentMap());
            fileManager.saveScore(scoreManager.getScores());
            JOptionPane.showMessageDialog(this, "数据保存成功！");
            updateStatus("数据已保存");
        });
        
        loadItem.addActionListener(e -> {
            Map<String, Student> loadedStudents = fileManager.loadStudents();
            Map<String, Score> loadedScores = fileManager.loadScores();
            
            studentManager.getStudentMap().clear();
            studentManager.getStudentMap().putAll(loadedStudents);
            
            scoreManager.getScores().clear();
            scoreManager.getScores().putAll(loadedScores);
            
            JOptionPane.showMessageDialog(this, "数据加载成功！");
            updateStatus("数据已加载");
            
            // 刷新各面板
            studentPanel.refreshData();
            scorePanel.refreshData();
            statisticsPanel.refreshData();
        });
        
        backupItem.addActionListener(e -> {
            fileManager.saveBackup();
            JOptionPane.showMessageDialog(this, "数据备份成功！");
            updateStatus("数据已备份");
        });
        
        exitItem.addActionListener(e -> {
            int option = JOptionPane.showConfirmDialog(
                    this,
                    "是否要退出系统？",
                    "退出确认",
                    JOptionPane.YES_NO_OPTION);
            
            if (option == JOptionPane.YES_OPTION) {
                System.exit(0);
            }
        });
        
        fileMenu.add(saveItem);
        fileMenu.add(loadItem);
        fileMenu.add(backupItem);
        fileMenu.addSeparator();
        fileMenu.add(exitItem);
        
        // 主题菜单
        themeMenu = new JMenu("主题");
        themeMenu.setForeground(Color.WHITE);
        themeMenu.setFont(ThemeManager.NORMAL_FONT);
        
        JMenuItem defaultThemeItem = new JMenuItem("默认主题");
        JMenuItem darkThemeItem = new JMenuItem("深色主题");
        
        defaultThemeItem.setFont(ThemeManager.NORMAL_FONT);
        darkThemeItem.setFont(ThemeManager.NORMAL_FONT);
        
        defaultThemeItem.addActionListener(e -> applyDefaultTheme());
        darkThemeItem.addActionListener(e -> applyDarkTheme());
        
        themeMenu.add(defaultThemeItem);
        themeMenu.add(darkThemeItem);
        
        // 帮助菜单
        helpMenu = new JMenu("帮助");
        helpMenu.setForeground(Color.WHITE);
        helpMenu.setFont(ThemeManager.NORMAL_FONT);
        
        JMenuItem aboutItem = new JMenuItem("关于");
        aboutItem.setFont(ThemeManager.NORMAL_FONT);
        
        aboutItem.addActionListener(e -> {
            JOptionPane.showMessageDialog(this,
                    "学生管理系统 v2.0\n" +
                            "功能增强版\n" +
                            "Copyright © 2025\n" +
                            "新增功能：\n" +
                            "- 学生信息搜索与导出\n" +
                            "- 成绩管理搜索与导出\n" +
                            "- 数据可视化图表\n" +
                            "- 主题切换功能\n" +
                            "- 状态栏实时信息",
                    "关于",
                    JOptionPane.INFORMATION_MESSAGE);
        });
        
        helpMenu.add(aboutItem);
        
        // 添加菜单到菜单栏
        menuBar.add(fileMenu);
        menuBar.add(themeMenu);
        menuBar.add(helpMenu);
        
        // 设置菜单栏
        setJMenuBar(menuBar);
    }
    
    /**
     * 应用默认主题
     */
    private void applyDefaultTheme() {
        // 这里可以实现主题切换逻辑
        JOptionPane.showMessageDialog(this, "默认主题已应用！");
    }
    
    /**
     * 应用深色主题
     */
    private void applyDarkTheme() {
        // 这里可以实现深色主题逻辑
        JOptionPane.showMessageDialog(this, "深色主题已应用！");
    }
    
    /**
     * 创建状态栏
     */
    private JPanel createStatusBar() {
        JPanel statusBar = new JPanel(new BorderLayout());
        statusBar.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
        statusBar.setBackground(ThemeManager.PRIMARY_COLOR);
        
        statusLabel = new JLabel("学生管理系统 - 就绪");
        statusLabel.setForeground(Color.WHITE);
        statusLabel.setFont(ThemeManager.SMALL_FONT);
        
        JLabel versionLabel = new JLabel("版本 2.0");
        versionLabel.setForeground(Color.WHITE);
        versionLabel.setFont(ThemeManager.SMALL_FONT);
        
        statusBar.add(statusLabel, BorderLayout.WEST);
        statusBar.add(versionLabel, BorderLayout.EAST);
        
        return statusBar;
    }
    
    /**
     * 更新状态栏信息
     */
    private void updateStatus(String message) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        statusLabel.setText("学生管理系统 - " + message + " - " + now.format(formatter));
    }
    
    /**
     * 启动状态栏定时更新
     */
    private void startStatusUpdate() {
        Timer timer = new Timer(1000, e -> {
            // 更新学生和成绩数量信息
            int studentCount = studentManager.getStudentMap().size();
            int scoreCount = scoreManager.getScores().size();
            updateStatus("学生: " + studentCount + "人, 成绩: " + scoreCount + "条记录");
        });
        timer.start();
    }
}